package org.apple.averager;

import java.util.Properties;
import java.util.Vector;

import org.apple.data.SensorReading;
import org.apple.databanker.*;
import org.apple.data.*;

import org.apple.sensor.driver.UninitializedException;
import org.apple.util.*;

public class WindSpeedAverager implements Averager {

	private int HighWeight;
	private int LowWeight;
	private DataBanker databanker;

	public WindSpeedAverager() {
		Configure configure = Configure.instance();

		HighWeight = Integer.parseInt(configure
				.getProperty("windSpeedHighWeight"));
		LowWeight = Integer.parseInt(configure
				.getProperty("windSpeedLowWeight"));

	}

	public SensorReading average() {

		double weight = 0;
		double windspeed = 0;
		double value = 0;
		Properties prop = Configure.instance();

		SensorReading sensorreading = new SensorReading(SensorReading.SPEED, 0);
		Vector SensorReadings = new Vector();
		try {
			databanker = (DataBanker) Class.forName(
					prop.getProperty("dataBankerType")).newInstance();
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		databanker.read(SensorReadings, SensorReading.SPEED);

		SensorReading sr = new SensorReading(0, 0, 0);
		if (SensorReadings.size() == 0) {
			windspeed = SensorReading.NOSPEED;
			System.out
					.print("The data banker has no readings, please try again");
		} else {
			for (int i = 0; i < SensorReadings.size(); i++) {
				sr = (SensorReading) SensorReadings.elementAt(i);
				if (sr.getResolutionType() == SensorResolution.HighRes) {
					value = sr.getValue() * HighWeight + value;
					weight = weight + HighWeight;
				} else {
					value = sr.getValue() * LowWeight + value;
					weight = weight + LowWeight;
				}

			}
			windspeed = value / weight;
			
		}

		sensorreading.setValue(windspeed);
		return sensorreading;
	}

}
